<template>
  <div class="mobile-dashboard">
    <!-- 欢迎卡片 -->
    <div class="welcome-card">
      <div class="welcome-content">
        <h2 class="welcome-title">欢迎回来</h2>
        <p class="welcome-subtitle">{{ getCurrentTime() }}</p>
      </div>
      <div class="welcome-avatar">
        <el-avatar :size="50">
          <el-icon><User /></el-icon>
        </el-avatar>
      </div>
    </div>

    <!-- 快捷操作 -->
    <div class="quick-actions">
      <h3 class="section-title">快捷操作</h3>
      <div class="action-grid">
        <div class="action-item" @click="quickAction('param-engine')">
          <div class="action-icon param">
            <el-icon><Cpu /></el-icon>
          </div>
          <span class="action-label">参数引擎</span>
        </div>
        <div class="action-item" @click="quickAction('data-collection')">
          <div class="action-icon collection">
            <el-icon><Upload /></el-icon>
          </div>
          <span class="action-label">数据采集</span>
        </div>
        <div class="action-item" @click="quickAction('anomaly-detection')">
          <div class="action-icon alert">
            <el-icon><Warning /></el-icon>
          </div>
          <span class="action-label">异常监测</span>
        </div>
        <div class="action-item" @click="quickAction('prediction-analysis')">
          <div class="action-icon predict">
            <el-icon><TrendCharts /></el-icon>
          </div>
          <span class="action-label">预测分析</span>
        </div>
      </div>
    </div>

    <!-- 海关监管模块 -->
    <div class="customs-modules">
      <h3 class="section-title">海关监管模块</h3>
      <div class="module-grid">
        <div class="module-item" @click="quickAction('query-analysis')">
          <div class="module-icon query">
            <el-icon><Search /></el-icon>
          </div>
          <span class="module-label">查询分析</span>
        </div>
        <div class="module-item" @click="quickAction('system-management')">
          <div class="module-icon system">
            <el-icon><Tools /></el-icon>
          </div>
          <span class="module-label">系统管理</span>
        </div>
        <div class="module-item" @click="quickAction('risk-control')">
          <div class="module-icon risk">
            <el-icon><Lock /></el-icon>
          </div>
          <span class="module-label">风险控制</span>
        </div>
        <div class="module-item" @click="quickAction('customs-clearance')">
          <div class="module-icon clearance">
            <el-icon><Document /></el-icon>
          </div>
          <span class="module-label">通关管理</span>
        </div>
      </div>
    </div>

    <!-- 分类数据展示 -->
    <div v-if="categoryData.length > 0" class="category-section">
      <h3 class="section-title">参数分类数据</h3>
      <div class="category-list">
        <div v-for="category in categoryData" :key="category.id" class="category-item">
          <div class="category-icon">{{ getCategoryIcon(category.categoryCode) }}</div>
          <div class="category-info">
            <h4>{{ category.categoryName }}</h4>
            <p>{{ category.description }}</p>
            <span class="category-code">{{ category.categoryCode }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 系统统计 -->
    <div class="stats-section">
      <h3 class="section-title">系统状态</h3>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-card class="stat-card" @click="viewDetail('params')">
            <div class="stat-item">
              <div class="stat-icon primary">
                <el-icon><Cpu /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ systemStats.totalParams }}</div>
                <div class="stat-label">系统参数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="stat-card" @click="viewDetail('data')">
            <div class="stat-item">
              <div class="stat-icon success">
                <el-icon><DataAnalysis /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ systemStats.dataRecords }}</div>
                <div class="stat-label">数据记录</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="stat-card" @click="viewDetail('anomalies')">
            <div class="stat-item">
              <div class="stat-icon warning">
                <el-icon><Warning /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ systemStats.anomalies }}</div>
                <div class="stat-label">异常监测</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="stat-card" @click="viewDetail('users')">
            <div class="stat-item">
              <div class="stat-icon info">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ systemStats.activeUsers }}</div>
                <div class="stat-label">在线用户</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 系统状态 -->
    <div class="system-status">
      <h3 class="section-title">运行状态</h3>
      <el-card class="status-overview">
        <div class="status-list">
          <div class="status-row">
            <div class="status-dot success"></div>
            <span class="status-name">参数引擎</span>
            <span class="status-value">正常</span>
          </div>
          <div class="status-row">
            <div class="status-dot success"></div>
            <span class="status-name">数据库</span>
            <span class="status-value">连接正常</span>
          </div>
          <div class="status-row">
            <div class="status-dot" :class="redisUsageLevel"></div>
            <span class="status-name">Redis缓存</span>
            <span class="status-value">{{ redisDisplay }}</span>
          </div>
                  <div class="status-row">
          <div class="status-dot success"></div>
          <span class="status-name">AI服务</span>
          <span class="status-value">运行中</span>
        </div>
        <div class="status-row">
          <div class="status-dot" :class="connectionStatus === 'connected' ? 'success' : 'error'"></div>
          <span class="status-name">后端连接</span>
          <span class="status-value">{{ connectionStatus === 'connected' ? '连接正常' : '连接失败' }}</span>
        </div>
        </div>
      </el-card>
    </div>

    <!-- 最近活动 -->
    <div class="recent-activity">
      <h3 class="section-title">最近活动</h3>
      <el-card class="activity-card">
        <div class="activity-list">
          <div class="activity-item" v-for="activity in recentActivities" :key="activity.id">
            <div class="activity-icon" :class="activity.type">
              <el-icon><Bell /></el-icon>
            </div>
            <div class="activity-content">
              <h4 class="activity-title">{{ activity.title }}</h4>
              <p class="activity-desc">{{ activity.description }}</p>
              <span class="activity-time">{{ activity.time }}</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  User, Cpu, DataAnalysis, Warning, Upload, TrendCharts, Bell, CircleCheck,
  Search, Tools, Lock, Document
} from '@element-plus/icons-vue'
import { getSystemStats, getRecentActivities, healthCheck, getSystemStatus, getRedisStats } from '@/assets/api/dashboard'
import { getRealCategories, getCategoryTree } from '@/assets/api/mobile'

const router = useRouter()

// 系统统计数据
const systemStats = reactive({
  totalParams: 0,
  dataRecords: '0',
  anomalies: 0,
  activeUsers: 0
})

// 最近活动数据
const recentActivities = ref([])

// 连接状态
const connectionStatus = ref('disconnected')
const redisStats = reactive({ definitionHitRate: '0%', valueHitRate: '0%', lastUpdate: '' })

// API测试相关
const apiLoading = reactive({
  health: false,
  stats: false,
  status: false,
  categories: false
})
const apiTestResult = ref(null)

// 真实数据
const realData = reactive({
  categoryCount: 0,
  healthStatus: '',
})
const realDataLoading = ref(false)

// 分类数据
const categoryData = ref([])

// 加载系统数据
const loadSystemData = async () => {
  try {
    // 获取系统统计
    const stats = await getSystemStats()
    Object.assign(systemStats, stats.data || stats)
    
    // 获取最近活动
    const activities = await getRecentActivities()
    recentActivities.value = activities.data || activities
    
    // 获取Redis指标
    const r = await getRedisStats()
    Object.assign(redisStats, r.data || r)
    
    // 更新连接状态
    connectionStatus.value = 'connected'
  } catch (error) {
    console.error('加载系统数据失败:', error)
    connectionStatus.value = 'disconnected'
    
    // 使用默认数据
    Object.assign(systemStats, {
      totalParams: 156,
      dataRecords: '2.3M',
      anomalies: 23,
      activeUsers: 8
    })
    
    recentActivities.value = [
      {
        id: 1,
        type: 'success',
        title: '参数更新',
        description: '数据库连接池参数已成功更新',
        time: '2分钟前'
      },
      {
        id: 2,
        type: 'warning',
        title: 'AI推荐',
        description: '建议优化缓存TTL配置以提升性能',
        time: '15分钟前'
      },
      {
        id: 3,
        type: 'info',
        title: '系统备份',
        description: '每日自动备份任务执行完成',
        time: '1小时前'
      }
    ]
  }
}

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date()
  const hour = now.getHours()
  if (hour < 12) return '上午好'
  if (hour < 18) return '下午好'
  return '晚上好'
}

// 快捷操作
const quickAction = async (action) => {
  switch (action) {
    case 'param-engine':
      router.push('/param-engine/dashboard')
      break
    case 'data-collection':
      ElMessage.info('数据采集模块开发中，包含FTP采集、文件上传等功能')
      break
    case 'anomaly-detection':
      ElMessage.info('异常监测系统开发中，包含智能检测、预警管理等功能')
      break
    case 'prediction-analysis':
      ElMessage.info('预测分析模块开发中，包含ARIMA预测、趋势分析等功能')
      break
    case 'query-analysis':
      ElMessage.info('查询分析模块开发中，包含数据查询、报表统计等功能')
      break
    case 'system-management':
      ElMessage.info('系统管理模块开发中，包含用户管理、角色权限、系统日志等功能')
      break
    case 'risk-control':
      ElMessage.info('风险控制模块开发中，包含风险评估、智能预警等功能')
      break
    case 'customs-clearance':
      ElMessage.info('通关管理模块开发中，包含申报管理、通关流程等功能')
      break
  }
}

// 已移除连接测试功能，现在使用运行状态展示连接状态

// 查看详情
const viewDetail = (type) => {
  switch (type) {
    case 'params':
      router.push('/param-engine/definitions')
      break
    case 'data':
      ElMessage.info('数据详情功能开发中')
      break
    case 'anomalies':
      ElMessage.info('异常详情功能开发中')
      break
    case 'users':
          ElMessage.info('用户详情功能开发中')
    break
  }
}

// API测试功能
const testApi = async (type) => {
  apiLoading[type] = true
  try {
    let result = null
    switch (type) {
      case 'health':
        result = await healthCheck()
        break
      case 'stats':
        result = await getSystemStats()
        break
      case 'status':
        result = await getSystemStatus()
        break
      case 'categories':
        result = await getRealCategories()
        break
    }
    apiTestResult.value = result
    ElMessage.success(`${type} API测试成功`)
    connectionStatus.value = 'connected'
  } catch (error) {
    console.error(`${type} API测试失败:`, error)
    apiTestResult.value = { error: error.message }
    ElMessage.error(`${type} API测试失败`)
    connectionStatus.value = 'disconnected'
  } finally {
    apiLoading[type] = false
  }
}

// 加载真实数据
const loadRealData = async () => {
  realDataLoading.value = true
  try {
    // 并行加载多个API
    const [healthResult, categoriesResult] = await Promise.all([
      healthCheck(),
      getRealCategories()
    ])
    
    // 处理健康检查结果
    realData.healthStatus = healthResult?.status || healthResult?.data?.status || 'UP'
    
    // 处理分类数据
    if (categoriesResult && categoriesResult.data) {
      const categories = Array.isArray(categoriesResult.data) ? categoriesResult.data : []
      categoryData.value = categories
      realData.categoryCount = categories.length
    }
    
    connectionStatus.value = 'connected'
  } catch (error) {
    console.error('加载真实数据失败:', error)
    connectionStatus.value = 'disconnected'
    ElMessage.error('加载真实数据失败')
  } finally {
    realDataLoading.value = false
  }
}

// 获取分类图标
const getCategoryIcon = (categoryCode) => {
  const iconMap = {
    'DB_CONFIG': '🗄️',
    'CACHE_CONFIG': '⚡',
    'SYS_CONFIG': '⚙️',
    'REDIS_CONFIG': '🔴',
    'LOCAL_CACHE': '💾'
  }
  return iconMap[categoryCode] || '📁'
}

// 计算展示与颜色
const parsePercent = (val) => {
  if (typeof val === 'number') return val
  const n = Number(String(val).replace('%',''))
  return isNaN(n) ? 0 : n
}
const redisUsageLevel = computed(() => {
  const rate = Math.max(parsePercent(redisStats.valueHitRate), parsePercent(redisStats.definitionHitRate))
  if (rate < 60) return 'error' // 命中率低
  if (rate < 85) return 'warning'
  return 'success'
})
const redisDisplay = computed(() => {
  const v = redisStats.valueHitRate || '0%'
  return `命中率 ${v}`
})

// 组件挂载时加载数据
onMounted(() => {
  loadSystemData()
  loadRealData()
})
</script>

<style scoped>
.mobile-dashboard {
  padding: 16px;
  padding-bottom: 100px; /* 为底部导航留出空间 */
}

/* 欢迎卡片 */
.welcome-card {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  border-radius: 16px;
  padding: 24px;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(24, 144, 255, 0.3);
}

.welcome-title {
  font-size: 22px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.welcome-subtitle {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
}

/* 快捷操作 */
.quick-actions {
  margin-bottom: 24px;
}

/* 海关监管模块 */
.customs-modules {
  margin-bottom: 24px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #262626;
  margin: 0 0 16px 0;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 12px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-item:active {
  transform: scale(0.95);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.action-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8px;
  font-size: 24px;
  color: white;
}

.action-icon.param {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
}

.action-icon.collection {
  background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
}

.action-icon.alert {
  background: linear-gradient(135deg, #fa8c16 0%, #d48806 100%);
}

.action-icon.predict {
  background: linear-gradient(135deg, #722ed1 0%, #531dab 100%);
}

.action-label {
  font-size: 12px;
  color: #262626;
  font-weight: 500;
  text-align: center;
}

/* 海关监管模块样式 */
.module-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

.module-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 8px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.module-item:active {
  transform: scale(0.95);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.module-icon {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 6px;
  font-size: 20px;
  color: white;
}

.module-icon.query {
  background: linear-gradient(135deg, #13c2c2 0%, #08979c 100%);
}

.module-icon.system {
  background: linear-gradient(135deg, #ff7a45 0%, #d73027 100%);
}

.module-icon.risk {
  background: linear-gradient(135deg, #f759ab 0%, #c41d7f 100%);
}

.module-icon.clearance {
  background: linear-gradient(135deg, #73d13d 0%, #52c41a 100%);
}

.module-label {
  font-size: 12px;
  color: #262626;
  font-weight: 500;
  text-align: center;
}

/* 系统统计 */
.stats-section {
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:active {
  transform: scale(0.98);
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 16px;
}

.stat-icon {
  width: 40px;
  height: 40px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 20px;
  color: white;
}

.stat-icon.primary {
  background: #1890ff;
}

.stat-icon.success {
  background: #52c41a;
}

.stat-icon.warning {
  background: #fa8c16;
}

.stat-icon.info {
  background: #722ed1;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #262626;
  margin-bottom: 2px;
}

.stat-label {
  font-size: 13px;
  color: #8c8c8c;
}

/* 系统状态 */
.system-status {
  margin-bottom: 24px;
}

.status-overview {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.status-list {
  padding: 16px;
}

.status-row {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.status-row:last-child {
  border-bottom: none;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 12px;
}

.status-dot.success {
  background: #52c41a;
}

.status-dot.warning {
  background: #fa8c16;
}

.status-dot.error {
  background: #ff4d4f;
}

.status-name {
  flex: 1;
  font-size: 14px;
  color: #262626;
}

.status-value {
  font-size: 13px;
  color: #8c8c8c;
}

/* 最近活动 */
.recent-activity {
  margin-bottom: 24px;
}

.activity-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.activity-list {
  padding: 16px;
}

.activity-item {
  display: flex;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.activity-item:last-child {
  border-bottom: none;
}

.activity-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 16px;
  flex-shrink: 0;
}

.activity-icon.success {
  background: #f6ffed;
  color: #52c41a;
}

.activity-icon.warning {
  background: #fff7e6;
  color: #fa8c16;
}

.activity-icon.info {
  background: #f0f5ff;
  color: #1890ff;
}

.activity-content {
  flex: 1;
}

.activity-title {
  font-size: 14px;
  font-weight: 600;
  color: #262626;
  margin: 0 0 4px 0;
}

.activity-desc {
  font-size: 13px;
  color: #8c8c8c;
  margin: 0 0 4px 0;
  line-height: 1.4;
}

.activity-time {
  font-size: 12px;
  color: #bfbfbf;
}

/* API测试部分 */
.api-test-section {
  margin-bottom: 24px;
}

.test-buttons {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
  margin-bottom: 16px;
}

.test-result {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.test-result h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.test-result pre {
  margin: 0;
  font-size: 12px;
  line-height: 1.4;
  max-height: 200px;
  overflow-y: auto;
  background: white;
  padding: 8px;
  border-radius: 4px;
}

/* 真实数据部分 */
.real-data-section {
  margin-bottom: 24px;
}

.real-data-section .section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.data-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.data-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.data-item:last-child {
  border-bottom: none;
}

.data-label {
  font-size: 14px;
  color: #666;
}

.data-value {
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.data-value.success {
  color: #52c41a;
}

.data-value.error {
  color: #ff4d4f;
}

/* 分类数据部分 */
.category-section {
  margin-bottom: 24px;
}

.category-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.category-item {
  background: white;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
}

.category-icon {
  font-size: 24px;
  margin-right: 12px;
  width: 40px;
  text-align: center;
}

.category-info {
  flex: 1;
}

.category-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  color: #333;
}

.category-info p {
  margin: 0 0 6px 0;
  font-size: 13px;
  color: #666;
  line-height: 1.4;
}

.category-code {
  font-size: 12px;
  color: #999;
  background: #f0f0f0;
  padding: 2px 6px;
  border-radius: 4px;
}

/* 响应式优化 */
@media (max-width: 375px) {
  .action-grid {
    grid-template-columns: repeat(4, 1fr);
    gap: 8px;
  }
  
  .action-item {
    padding: 16px 8px;
  }
  
  .action-icon {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }
  
  .action-label {
    font-size: 11px;
  }
  
  .test-buttons {
    grid-template-columns: 1fr;
    gap: 8px;
  }
}
</style>


